Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
Is there a better way to write out long JavaScript "if" blocks

The following if-block seems really inefficient. I imagine there is a better way to do this.
This will be used to set parameters in a graphics library. eg camera position, objects position, and others.
Additionally, a generic solution is welcome.

const queryString = window.location.search;
const urlParameter = new URLSearchParams(queryString);
//this code is what my question is about V
if (urlParameter.has("a")) {
  a = parseInt(urlParameter.get("a"));
}
if (urlParameter.has("b")) {
  b = parseInt(urlParameter.get("b"));
}
if (urlParameter.has("c")) {
  c = parseInt(urlParameter.get("c"));
}
if (urlParameter.has("d")) {
  d = parseInt(urlParameter.get("d"));
}
//^

Note: I am fairly inexperienced with JavaScript, and mainly use it for hobby projects.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of storing them as individual variables, you are probably better of storing them in an object or Map instance. This allows for a more dynamic approach when setting/getting the values.

const allowedParameters = ["a", "b", "c", "d"];
const values = {};
for (const paramName of allowedParameters) {
  if (urlParameter.has(paramName)) {
    values[paramName] = parseInt(urlParameter.get(paramName));
  }
}

You can then access the values through values.a (or values["a"]), values.b, etc.


If you do want to store them as individual variables you could use destructuring assignment, this does assume that the variables are not defined beforehand.

const [a, b, c, d] = ["a", "b", "c", "d"].map((paramName) => {
  if (urlParameter.has(paramName)) {
    return parseInt(urlParameter.get(paramName));
  }
});

The above will set a, b, c, and d regardless of their presence in urlParameter. If they are not present they will be set to undefined, because the map() callback returns undefined if not present (it has no return value).

Meaning that this solution won't work if a, b, c, and d are already defined, and you only want to redefine them if present.


This can be solved with the solution below, but this will only work when redefining variables, not if you are initializing them for the first time.

[a, b, c, d] = Object.entries({ a, b, c, d }).map((paramName, oldValue) => {
  if (urlParameter.has(paramName)) {
    return parseInt(urlParameter.get(paramName));
  } else {
    return oldValue;
  }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use an array with the input parameter names an iterate over it.

But since you cannot assign dynamic variable names in JavaScript, you will need to change your output slightly to use an object:

const allowedParameters = ['a', 'b', 'c', 'd'];

const parsedParameters = {};

allowedParameters.forEach((key)=> {
  if (urlParameter.has(key)) {
    parsedParameters[key] = parseInt(urlParameter.get(key));
  }
});

// To use the values just access each key in the parsedParameters object:

console.log(parsedParameters.a); 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda